#include "ringqueue_test.hpp"
#include "task.hpp"

#include <iostream>
#include <unistd.h>

struct ThreadData
{
    RingQueue<Task>* rq;
    std::string threadname;
};

void* Comsumer(void* args)
{
    
    ThreadData* td = static_cast<ThreadData*>(args);
    RingQueue<Task>* rq = td->rq;
    std::string threadname = td->threadname;

    while(true)
    {

        Task task;
        rq->Pop(&task);

        task();
        std::cout << "get task:" << task.GetTask()
        << "---handle task:" << task.GetResult()
        << "---" << threadname << std::endl;
    }
    
    delete td;
}

void* Productor(void* args)
{
    ThreadData* td = static_cast<ThreadData*>(args);
    RingQueue<Task>* rq = td->rq;
    std::string threadname = td->threadname;

    while(true)
    {
        int data1 = rand() % 10 + 1;
        int data2 = rand() % 10;
        char op = opers[rand() % opers.size()];
        Task task(data1, data2, op);

        rq->Push(task);
        std::cout << "push task:" 
        << task.GetTask()
        << "---" << threadname << std::endl;

        sleep(1);
    }
    
    delete td;
}

int main()
{
    srand(time(nullptr));

    RingQueue<Task>* rq = new RingQueue<Task>();

    pthread_t comsumer[3], productor[3];
    for(int i=0; i<3; i++)
    {
        ThreadData* td = new ThreadData();
        td->rq = rq;
        td->threadname = "comsumer-" + std::to_string(i);
        pthread_create(comsumer+i, nullptr, Comsumer, (void*)td);
    }
    for(int i=0; i<3; i++)
    {
        ThreadData* td = new ThreadData();
        td->rq = rq;
        td->threadname = "productor-" + std::to_string(i);
        pthread_create(productor+i, nullptr, Productor, (void*)td);
    }

    for(int i=0; i<3; i++)
    {
        pthread_join(comsumer[i], nullptr);
    }
    for(int i=0; i<3; i++)
    {
        pthread_join(productor[i], nullptr);
    }

    return 0;
}